package org.example;

import java.sql.*;

public class TransactionTest {
    private static final String URL = "jdbc:mysql://localhost:3306/test";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    private static Connection conn = null;

    /**
     * 初始化数据库连接
     */
    public static void initializeConnection() throws ClassNotFoundException, SQLException {
        Class.forName(DRIVER);
        conn = DriverManager.getConnection(URL, USER, PASSWORD);
        // 设置自动提交为false，开启事务管理
        conn.setAutoCommit(false);
        System.out.println("数据库连接成功，事务模式已开启");
    }

    /**
     * 使用事务同时新增两个教师
     * 如果任何一个插入失败，整个事务回滚
     */
    public static void addTwoTeachersWithTransaction(Teacher teacher1, Teacher teacher2) {
        String sql = "INSERT INTO teacher (id, name, trs, birthday) VALUES (?, ?, ?, ?)";

        try {
            System.out.println("开始事务操作...");

            // 插入第一个教师
            try (PreparedStatement pstmt1 = conn.prepareStatement(sql)) {
                pstmt1.setInt(1, teacher1.getId());
                pstmt1.setString(2, teacher1.getName());
                pstmt1.setString(3, teacher1.getTrs());
                pstmt1.setDate(4, new java.sql.Date(teacher1.getBirthday().getTime()));

                int rows1 = pstmt1.executeUpdate();
                System.out.println("第一个教师插入结果: " + rows1 + " 行受影响");
            }

            // 插入第二个教师
            try (PreparedStatement pstmt2 = conn.prepareStatement(sql)) {
                pstmt2.setInt(1, teacher2.getId());
                pstmt2.setString(2, teacher2.getName());
                pstmt2.setString(3, teacher2.getTrs());
                pstmt2.setDate(4, new java.sql.Date(teacher2.getBirthday().getTime()));

                int rows2 = pstmt2.executeUpdate();
                System.out.println("第二个教师插入结果: " + rows2 + " 行受影响");
            }

            // 如果都成功，提交事务
            conn.commit();
            System.out.println("事务提交成功！两个教师都已添加到数据库");

        } catch (SQLException e) {
            System.out.println("事务执行失败: " + e.getMessage());
            System.out.println("执行事务回滚...");

            try {
                if (conn != null) {
                    conn.rollback();
                    System.out.println("事务回滚成功！所有操作已撤销");
                }
            } catch (SQLException rollbackEx) {
                System.out.println("回滚失败: " + rollbackEx.getMessage());
                rollbackEx.printStackTrace();
            }
        }
    }


    /**
     * 教师实体类
     */
    static class Teacher {
        private int id;
        private String name;
        private String trs;
        private Date birthday;

        public Teacher(int id, String name, String trs, Date birthday) {
            this.id = id;
            this.name = name;
            this.trs = trs;
            this.birthday = birthday;
        }

        // Getter方法
        public int getId() { return id; }
        public String getName() { return name; }
        public String getTrs() { return trs; }
        public Date getBirthday() { return birthday; }
    }

    public static void main(String[] args) {
        try {
            // 1. 初始化连接和表
            initializeConnection();


            // 2. 显示初始数据
            System.out.println("\n=== 初始数据 ===");


            // 3. 测试成功的事务
            System.out.println("\n=== 测试成功的事务 ===");
            Teacher teacher1 = new Teacher(101, "zhangsan", "yf201", Date.valueOf("1980-05-15"));
            Teacher teacher2 = new Teacher(102, "qikasi", "ww008", Date.valueOf("1978-08-20"));
            addTwoTeachersWithTransaction(teacher1, teacher2);

            // 5. 再次测试成功的事务
            System.out.println("\n=== 再次测试成功的事务 ===");


        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}